package com.itheima.reggie.controller;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Employee;
import com.itheima.reggie.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/employee")
public class EmployeeController {
    @Autowired
    private EmployeeService employeeService;

    /**
     * 员工登录
     * @param request
     * @param employee
     * @return
     */
    @PostMapping("/login")
    public R<Employee> login(HttpServletRequest request, @RequestBody Employee employee){
        /*
        1.将页面提交的密码password进行md5加密处理, 得到加密后的字符串
        2.根据页面提交的用户名username查询数据库中员工数据信息
        3.如果没有查询到, 则返回登录失败结果
        4.密码比对，如果不一致, 则返回登录失败结果
        5.查看员工状态，如果为已禁用状态，则返回员工已禁用结果
        6.登录成功，将员工id存入Session, 并返回登录成功结果
        */

        if (employee == null
                || StringUtils.isEmpty(employee.getUsername())
                || StringUtils.isEmpty(employee.getPassword())){
            return R.error("用户名或密码不能为空...");
        }
//    1.将页面提交的密码password进行md5加密处理, 得到加密后的字符串
        String password = DigestUtils.md5DigestAsHex(employee.getPassword().getBytes());
//    2.根据页面提交的用户名username查询数据库中员工数据信息
        LambdaQueryWrapper<Employee> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Employee::getUsername,employee.getUsername());
        Employee emp = employeeService.getOne(lqw);
//    3.如果没有查询到, 则返回登录失败结果
        if (emp == null){
            return R.error("用户不存在!");
        }
//    4.密码比对，如果不一致, 则返回登录失败结果
        if(!emp.getPassword().equals(password)){
            return R.error("密码错误!");
        }
//    5.查看员工状态，如果为已禁用状态，则返回员工已禁用结果
        if (emp.getStatus() != 1){
            return R.error("账号已被禁用");
        }
//    6.登录成功，将员工信息存入Session, 并返回登录成功结果
        request.getSession().setAttribute("employee",emp);
        emp.setPassword(null);
        return R.success(emp);
    }

    /**
     * 退出登录
      * @param request
     * @return
     */
    @PostMapping("/logout")
    public R<String> logout(HttpServletRequest request){
        //清空session
        HttpSession session = request.getSession();
        /*//方式1
        session.invalidate();*/

        //方式2
        session.removeAttribute("employee");

        return R.success(null);
    }

    /**
     * 新增员工
     * @param employee
     * @return
     */
    @PostMapping
    public R<String> saveEmployee(@RequestBody Employee employee,HttpServletRequest request){
        /*LambdaQueryWrapper<Employee> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Employee::getUsername,employee.getUsername());
        Employee emp = employeeService.getOne(lqw);

        if (emp != null){
            return R.error("用户名"+emp.getUsername()+"已存在");
        }*/

        log.info("新增员工,员工信息为:{}",employee.toString());

        //检查表,找到需要进行处理的数据
        //1.设置初始密码
        String password = "123456";
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        //设置加密后的密码,DigestUtils.md5DigestAsHex
        employee.setPassword(password);
        /*//2.设置创建时间和修改时间,为当前系统时间   LocalDateTime.now()
        employee.setCreateTime(LocalDateTime.now());
        employee.setUpdateTime(LocalDateTime.now());
        //3.设置创建人和修改人,应该是当前登陆人
        Employee creatUser = (Employee)request.getSession().getAttribute("employee");
        log.info("创建人是:{}",creatUser.getName());
        employee.setCreateUser(creatUser.getId());
        employee.setUpdateUser(creatUser.getId());*/

        //4.将新员工信息存入数据库
        try {
            employeeService.save(employee);
            return R.success("新增成功");
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("保存失败");
        }
        /*if (save) {
            return R.success("新增成功");
        } else {
            return R.error("保存失败");
        }*/
    }

    /**
     * 员工信息分页查询
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R getByPageAndCondition(Integer page, Integer pageSize, String name){
        log.info("page = {},pageSize = {},name = {}",page,pageSize,name);

        /*//构造分页构造器
        Page pageInfo = new Page(page, pageSize);

        //构造条件构造器
        LambdaQueryWrapper<Employee> lqw = new LambdaQueryWrapper<>();
        //添加过滤条件
        lqw.like(StringUtils.isNotEmpty(name),Employee::getName,name);
        //添加排序条件
        lqw.orderByDesc(Employee::getUpdateTime);*/

        //执行查询
        Page pageInfo = new Page(page,pageSize);

        LambdaQueryWrapper<Employee> lqw = new LambdaQueryWrapper<>();
        lqw.like(StringUtils.isNotEmpty(name),Employee::getName,name);
        employeeService.page(pageInfo,lqw);

        List records = pageInfo.getRecords();
        int total = (int) pageInfo.getTotal();

        //只返回前端需要的数据
        Map data = new HashMap();
        data.put("records",records);
        data.put("total",total);

        return R.success(data);
    }

    /**
     * 根据id修改员工信息
     * @param request
     * @param employee
     * @return
     */
    @PutMapping
    public R<String> updateEmp(@RequestBody Employee employee,HttpServletRequest request){
        log.info(employee.toString());

        /*Employee creatUser = (Employee)request.getSession().getAttribute("employee");

        *//*employee.setUpdateUser(creatUser.getId());
        employee.setUpdateTime(LocalDateTime.now());*//*
        Long id = Thread.currentThread().getId();
        log.info("线程id为:{}",id);*/

        employeeService.updateById(employee);

        return R.success("修改成功");

    }

    /**
     * 根据id查询员工信息
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<Employee> getById(@PathVariable Long id){
        log.info("根据id查询员工信息...");
        Employee emp = employeeService.getById(id);
        if (emp != null){
            return R.success(emp);
        }
        return R.error("没有查询到员工信息");
    }

    @GetMapping("/export")
    public void R(HttpServletResponse response){
        //获取文件对象
        //File file = new File("D:\\img\\temp.xls");
        try {
            response.setHeader("Content-Disposition","attachment;filename=employee.xlsx");

            List<Employee> list = employeeService.list();
            list.forEach(employee -> {
                Long createUserId = employee.getCreateUser();
                String createName = employeeService.getById(createUserId).getName();
                employee.setCreateUserName(createName);
                Long updateUserId = employee.getUpdateUser();
                String updateUserName = employeeService.getById(updateUserId).getName();
                employee.setUpdateUserName(updateUserName);
            });

            ServletOutputStream outputStream = response.getOutputStream();

            EasyExcel.write(outputStream,Employee.class).sheet("员工数据").doWrite(list);

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
